<template>
  <el-card style="margin: 10px 15px" :body-style="{ padding: '20px' }">
    <template #header>
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="addOrEditTrademark(0, [])"
      >
        添加
      </el-button>
    </template>

    <el-table v-loading="loading" :data="tradeMarkList" stripe border>
      <el-table-column label="序号" type="index" width="100px" />
      <el-table-column label="品牌名称" prop="tmName" />
      <el-table-column label="品牌LOGO">
        <template slot-scope="scope">
          <el-image
            :src="scope.row.logoUrl"
            fit="fill"
            :lazy="true"
            style="width: 100px"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="small"
            style="margin-right: 10px"
            @click="addOrEditTrademark(1, scope.row)"
          >
            修改
          </el-button>
          <el-popconfirm
            title="是否确认删除?"
            confirm-button-text="确认"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            @onConfirm="delTrademark(scope.row.id)"
          >
            <el-button
              slot="reference"
              type="danger"
              icon="el-icon-delete"
              size="small"
            >
              删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page.sync="current"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="prev,pager,next,jumper,sizes,total"
      :total="total"
      @size-change="sizeChange"
      @current-change="currentChange"
    >
    </el-pagination>

    <el-dialog
      close-on-press-escape
      show-close
      :visible.sync="isDialog"
      :title="formData.id ? '修改品牌' : '添加品牌'"
      @close="closeDialog"
    >
      <el-form
        ref="formData"
        :rules="rules"
        :model="formData"
        :validate-on-rule-change="false"
        inline
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            v-model="formData.tmName"
            placeholder="请填写品牌名称"
            size="normal"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="fileUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="formData.logoUrl"
              :src="formData.logoUrl"
              class="avatar"
              alt="img"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="confirmHandler">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  reqAddOrEditTrademark,
  reqDelTradeMark,
  reqTrademarkListByPage,
} from "@/api/trademark";

export default {
  name: "Trademark",
  data() {
    return {
      tradeMarkList: [],
      total: 0,
      current: 1,
      page: 0,
      pageSize: 5,
      size: 0,
      orders: [],
      loading: false,
      isDialog: false,
      formData: {
        tmName: "",
        logoUrl: "",
      },
      rules: {
        tmName: [
          {
            required: true,
            message: "品牌名称必填",
            trigger: ["blur", "change"],
          },
          {
            min: 2,
            max: 20,
            message: "品牌名称字数大于2位小于20位",
            trigger: ["blur", "change"],
          },
        ],
        logoUrl: [
          { required: true, message: "品牌LOGO必选", trigger: "change" },
        ],
      },
      fileUrl: process.env.VUE_APP_BASE_API + `/product/upload`,
    };
  },
  mounted() {
    this.getTrademarkListByPage();
  },
  methods: {
    async getTrademarkListByPage() {
      try {
        this.loading = true;
        if (Number(this.current * this.pagesize) > this.total) {
          this.current = Math.ceil(this.total / this.pagesize);
        }
        const result = await reqTrademarkListByPage(
          this.current,
          this.pageSize
        );
        // console.log(result);
        this.current = result.current;
        this.page = result.page;
        this.pageSize = result.size;
        this.total = result.total;
        this.tradeMarkList = result.records;
        this.loading = false;
      } catch (e) {
        this.$message.error("获取商品列表错误");
        this.tradeMarkList = [];
        this.loading = false;
      }
    },
    sizeChange(val) {
      this.pageSize = val;
      this.getTrademarkListByPage();
    },
    currentChange(val) {
      this.current = val;
      this.getTrademarkListByPage();
    },
    addOrEditTrademark(type, row) {
      this.isDialog = true;
      if (type === 1) this.formData = { ...row };
      console.log(row);
      this.$nextTick(() => {
        this.$refs.formData.clearValidate();
      });
    },

    closeDialog() {
      this.formData = {
        tmName: "",
        logoUrl: "",
      };
    },
    handleAvatarSuccess(response) {
      this.formData.logoUrl = response.data;
    },
    beforeAvatarUpload(file) {
      const isJpg = file.type === "image/jpeg";
      const isSize = file.size / 1024 / 1024 < 2;
      if (!isJpg) {
        this.$message.error("请上传小于2M的图片");
      }
      if (!isSize) {
        this.$message.error("请上传Jpg格式的图片");
      }
      return isJpg & isSize;
    },
    async delTrademark(id) {
      try {
        await reqDelTradeMark(id);
        this.getTrademarkListByPage();
        this.$message.success("删除成功");
      } catch (e) {
        this.$message.error("删除失败");
      }
    },
    async confirmHandler() {
      this.$refs.formData.validate(async (valid) => {
        if (valid) {
          try {
            await reqAddOrEditTrademark(this.formData);
            this.isDialog = false;
            this.getTrademarkListByPage();
            this.$message.success(this.formData.id ? "修改成功" : "添加成功");
            // 处理一下当前页面 page
            // 用当前总的数据条数 % pageSize，如果值为 0 表示最后一页数据已经满了，否则还有剩余空间
            if (this.total % this.pageSize === 0) {
              // 没有剩余空间
              this.page = this.pages + 1;
            } else {
              // 有剩余空间
              this.page = this.pages;
            }
          } catch (e) {
            this.$message.success(this.formData.id ? "修改失败" : "添加失败");
          }
        } else {
          this.$message.error("请检查当前输入以及上传的格式问题！");
        }
      });
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
